package com.banzhi.shop.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.activity.GroupingDetailsActivity;
import com.banzhi.shop.activity.MainActivity;
import com.banzhi.shop.activity.WebViewActivity;
import com.banzhi.shop.adapter.GroupingPagerAdapter;
import com.banzhi.shop.adapter.GroupingPagerAdapter;
import com.banzhi.shop.data.GroupingIndexBean;
import com.banzhi.shop.data.GroupsadvBean;
import com.banzhi.shop.data.MessageEvent;
import com.banzhi.shop.model.CallBack.GroupingCallBack;
import com.banzhi.shop.model.Impl.GroupingImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.TabLayoutUtil;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.FlyBanner;
import com.banzhi.shop.view.NoScrollViewPager;
import com.banzhi.shop.view.TitleBar;
import com.banzhi.shop.view.VpSwipeRefreshLayout;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.moor.imkf.receiver.NetWorkReceiver;
import com.nostra13.universalimageloader.utils.L;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2018/7/17.
 */

public class GroupingFragment2 extends Fragment implements   GroupingCallBack, SwipeRefreshLayout.OnRefreshListener {

    private TitleBar mTbGrouping;
    private FlyBanner mBanner;
    private TabLayout mTabs;
    public NoScrollViewPager mViewPager;
    private List<String> mTitle = new ArrayList<String>();
    private ArrayList<Fragment> mFragment = new ArrayList<Fragment>();
    private GroupingPagerAdapter mPagerAdapter;
    private AppBarLayout mAppBarLayout;
    private VpSwipeRefreshLayout mVpSwipeRefesh;
    // 必须通过new 对象进行初始化
    private List<String> networkImages = new ArrayList<>();
    private GroupingImpl mModel;
    private int page = 1;
    private GroupingIndexBean mDatabean;
    private List<GroupsadvBean> mGroupsadv ;
    private int position;
 //   private RelativeLayout mRvChoiceGuige;

    private MainActivity mMainActivity;

  /*  private String[] mImagesUrl = {
            "http://img.banzhishenghuo.com/images/3/2018/03/kFpSN5fU65e69sE22BEsnN5NvuopfU.jpg",
            "http://img.banzhishenghuo.com/images/3/2018/05/i69GpY1ziGZs4G1Oqi2WIO2ZWqo6gN.png",
    };*/

    public NoScrollViewPager getViewPager(){
        return mViewPager;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_grouping2, container, false);
        //TODO 注册事件
    //    EventBus.getDefault().register(this);
        initView(view);
      //  initListener();

        mModel = new GroupingImpl();
        mModel.getData(page,20,GroupingFragment2.this);
        mPagerAdapter = new GroupingPagerAdapter(getFragmentManager(), mTitle, mFragment);
        mViewPager.setAdapter(mPagerAdapter);
        //为TabLayout设置ViewPager
        mTabs.setupWithViewPager(mViewPager);
        //使用ViewPager的适配器
        mTabs.setTabsFromPagerAdapter(mPagerAdapter);
        //定义tablayout下划线的长度
        mViewPager.setCurrentItem(0);
        mTabs.post(new Runnable() {
            @Override
            public void run() {
                TabLayoutUtil.setIndicator(mTabs, 55, 55);
            }
        });
        return view;
    }

    @Override
    public void onResume() {

     /*  // int id = GroupingFragment2.this.getIntent().getIntExtra("id",0);
        if (id ==1) {
            mMainActivity.getViewPager().setCurrentItem(1);
        }*/
        super.onResume();
    }
    /*    //TODO
    @Subscribe(threadMode = ThreadMode.MAIN ,sticky = true)
    public void onEvent(MessageEvent event) {
        LogUtils.e("event",event.toString());
      //  String data = event.getData();
    *//*    if (data.equals(" GroupingSelectFragment")) {  }*//*
            mViewPager.setCurrentItem(0);

    };*/
/*      @Override
  public void onDestroy() {
        super.onDestroy();
        //取消注册事件
     //   EventBus.getDefault().unregister(this);
    }*/

    private void initView(View view) {
        mTbGrouping = (TitleBar) view.findViewById(R.id.tb_grouping);
        mTbGrouping.setTitle("拼团");
        mBanner = (FlyBanner) view.findViewById(R.id.banner);
        mTabs = (TabLayout) view.findViewById(R.id.tabs);
        mViewPager = (NoScrollViewPager) view.findViewById(R.id.vp_fragment_grouping);
        mAppBarLayout = (AppBarLayout) view.findViewById(R.id.appBarLayout);
        mVpSwipeRefesh = (VpSwipeRefreshLayout) view.findViewById(R.id.vpSwipeRefreshLayout);
        mVpSwipeRefesh.setOnRefreshListener(this) ;

        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                  mVpSwipeRefesh.setEnabled(true);
                } else {
                  mVpSwipeRefesh.setEnabled(false);
                }
            }
        });
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        int height = width * 380 / 800;
        //  int height = width*216/319;
        LinearLayout.LayoutParams params = new AppBarLayout.LayoutParams(width, height);
        //获取当前控件的布局对象
        //params.height=width;//设置当前控件布局的高度
        mBanner.setLayoutParams(params);//将设置好的布局参数应用到控件中
        mTitle.add("团购精选");
        mTitle.add("我的拼团");
       /* MyGroupingFragments fragments0 = */

        mFragment.add(new GroupingSelectFragment());
        mFragment.add(new MyGroupingFragments().newInstance("0"));

    }



 /*   @Override
    public void onRefresh() {
        mModel.getData(page,20,GroupingFragment2.this);
        mVpSwipeRefesh.setRefreshing(false);

    }*/

    @Override
    public void ongetGroupingDataSuccess(Object object) {
      //  LogUtils.e("Grouping2", object.toString());
    //    mVpSwipeRefesh.setRefreshing(false);
        if (mVpSwipeRefesh.isRefreshing()) {
            mVpSwipeRefesh.setRefreshing(false);
        }
        mDatabean = (GroupingIndexBean) object;
        mGroupsadv = mDatabean.getGroupsadv();
        //轮播图加载网络图片
        initNetBanner();

    }

    private void initNetBanner() {
        if (mGroupsadv != null ) {
            for (int i = 0; i < mGroupsadv.size(); i++) {
                networkImages.add(mGroupsadv.get(i).getThumb());
            }
        }
      //  LogUtils.e("banner",networkImages.toString());
        if (networkImages.size() > 0) {
            mBanner.setImagesUrl(networkImages);
        }

        mBanner.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mGroupsadv != null) {
                    if (ASUtils.isCanUse(mGroupsadv.get(position).getLink())) {
                        if (ASUtils.isCanUse(mGroupsadv.get(position).getLinktype())) {
                            if ("2".equals(mGroupsadv.get(position).getLinktype())) {
                                Intent intent = new Intent(getContext(), GroupingDetailsActivity.class);
                                intent.putExtra("id", mGroupsadv.get(position).getLink());
                                startActivity(intent);
                            } else if ("1".equals(mGroupsadv.get(position).getLinktype())) {
                                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                intent.putExtra("data", mGroupsadv.get(position).getLink());
                                startActivity(intent);
                            }
                        }
                    }
                }

            }
        });
    }
    @Override
    public void ongetGroupingDataError(Object object) {
        if (mVpSwipeRefesh.isRefreshing()) {
            mVpSwipeRefesh.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void onRefresh() {
        mModel.getData(page,20,GroupingFragment2.this);
        // 显示充值成功的页面和需要的操作
        Intent intent = new Intent();
        intent.setAction("Refresh");
        getActivity().sendOrderedBroadcast(intent, null);   //有序广播发送
    }
}
